var request = require('request');
var PublishProxy = require('../../../proxy/publish.js');
var path = require('path');
var logger = require('log4js').getLogger();
var config = require('../../../config.json');
var fs = require('fs');
var url = require('url');
var http = require('http');

var getPostData = function (body) {
    var product_info = [];
    body.productsInfo.map(function (product) {
        product_info.push({
            "type": product.type,
            "version": product.version,
            "name": product.name,
            "fileName": path.basename(product.file)
        });
    });

    var publishInfo = {
        "name": body.publishName,
        "version": body.version,
        "publish_config": body.publishConfig_id,
        "product_info": product_info,
        "description": body.publishDescription
    };
    var goodsInfo = {
        "custom_data": body.custom_data,
        "img": body.goods_img,
        "introduction": body.goods_intro,
        "name": body.goodsName,
        "privacy": body.privacy,
        "supplier": body.supplier,
        "title": body.goodsTitle,
        "type": body.type,
        "version": body.version,
        "tag": body.tags,
        "dependency": body.goods_dependencies
    };
    return {publishInfo: publishInfo, goodsInfo: goodsInfo}
};

var publish_to_store = function (publish_id, goodsInfo,cb) {
    request.post({
        url: config.store.store_private + "/store/good",
        form: goodsInfo
    }, function (e, r, body) {
        if (e) {
            PublishProxy.updatePublishState(publish_id, "publish_failed", function () {
                messageBroker.emit('publish_state_update', {body: {state: "publish_failed"}, err:null});
                messageBroker.emit(publish_id, {task_id: publish_id, body: null, err: {msg:'商品发布到store失败'}});
                logger.error("发布到store失败：" + JSON.stringify(e));
            });
            return false;
        }
        logger.info("发布到store成功：" + JSON.stringify(r));
        PublishProxy.updatePublishState(publish_id, "published", cb);
    });
};

var upload_product_files = function (body, publish_id, type) {

    var upload_product_files;
    switch (type){
        case "mk":
            break;
        case "app":
            break;
        case "app_plugin":
            upload_product_files = require('./nectar_plugin_publish.js').upload_product_files;
            upload_product_files(body, publish_id);
            break;
        default:
            logger.error("无法处理的类型：" + type);
            break;
    }
};

var upload = function (name, filePath,type,version, cb) {
    request.get({
        url: config.store.store_private + "/store/create_upload?name=" + name + "&version="+ version +"&type=" + type,
        agentOptions: {
            secureProtocol: 'SSLv3_method'
        }
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            body = JSON.parse(body);
            if (body && body.data && body.data.url) {
                var href = url.parse(body.data.url);
                var toOptions = {
                    hostname: href.hostname,
                    port: href.port,
                    path: href.path,
                    method: 'PUT'
                };
                var file_Size = fs.statSync(filePath).size;
                var put_request = http.request(toOptions, function (response) {
                    logger.info(response.statusCode);
                    return cb(null, response.statusCode);
                }).on('error', function (e) {
                    logger.error('error' + e);
                    return cb(e);
                });
                var totalSize = file_Size;
                var passedLength = 0;
                var rs = fs.createReadStream(filePath, {autoClose: true});
                rs.on('data', function(chunk) {
                    passedLength += chunk.length;
                });
                setTimeout(
                    function show() {
                        var percent = Math.ceil((passedLength / totalSize) * 100);
                        if (passedLength < totalSize) {
                            PublishProxy.updatePublishState(publish_info._id, percent + '%' , function () {
                                messageBroker.emit('publish_state_update', {
                                    body: { msg:  percent + '%  ' },
                                    err: null
                                });
                                messageBroker.emit('product_uploading', {
                                    body: {publish_id: publish_info._id, msg:  percent + '%  '},
                                    err: null
                                });
                                setTimeout(show, 500);
                            });
                        }
                    },500);
                rs.pipe(put_request);
            }
        }else{
            var err = error || response.statusCode;
            logger.error('error occurred when upload the product:' + err);
            return cb(err);
        }

    })
};

exports.getPostData = getPostData;

exports.publish_to_store = publish_to_store;

exports.upload_product_files = upload_product_files;

exports.upload = upload;